<template>
    <div :class="className" :style="{height:height,width:width}" />
  </template>
  
  <script>
  import echarts from 'echarts'
  require('echarts/theme/macarons') // echarts theme
  import resize from './mixins/resize'
  
  export default {
    mixins: [resize],
    props: {
      className: {
        type: String,
        default: 'rank'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '350px'
      },
      autoResize: {
        type: Boolean,
        default: true
      },
      rankData: {
        type: Object,
        required: true
      }
    },
    data() {
      return {
        rank: null
      }
    },
    watch: {
      rankData: {
        deep: true,
        handler(val) {
          this.setOptions(val)
        }
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.initRank()
      }),
      setInterval(()=>{
      //模拟数据更新
      this.updateRankings();
      this.initRank();
    },3000);
    },
    beforeDestroy() {
      if (!this.rank) {
        return
      }
      this.rank.dispose()
      this.rank = null
    },
    methods: {
      initRank() {
        this.rank = echarts.init(this.$el, 'macarons')
        this.setOptions(this.rankData)
      },
      updateRankings(){
        //降序排名
        this.ranking.sort((a,b)=>b.point-a.point);
        //模拟数据更新
        this.ranking.forEach(academy=>{
            academy.point+=Math.floor(Math.random()*100);
        },1000);
        },

        setOptions({ xData, yData } = {}) {
            this.chart.setOption({
            
            grid: {
                top: 20,
                left: '1%',
                right: '1%',
                bottom: '1%',
                containLabel: true //删除背景网格线
            },
            xAxis:{
                data:xData,
                show:false //去掉xAxis轴
            },
            yAxis:{
                axisTick:{show:false},//去掉刻度
                axisLine:{show:false},//去掉轴线
            },
            series:[{
                data:this.ranking.map(academy=>academy.point),
                type:'bar'
            }]
        });
    },
    }
  }
  </script>
  